<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">考勤管理</span>
      <el-button type="primary" v-if="getUser.level >= 20" style="float: right; margin-top: 13px;" @click="beforeAddAttendance">
        新增记录
      </el-button>
      <el-button type="primary" style="float: right; margin: 13px 10px 0 0;" @click="clockIn">
        打卡/签退
      </el-button>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="100px" :model="attendanceForm" :rules="rules" ref="attendanceForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工" prop="employeeId">
              <el-select v-model="attendanceForm.employeeId" placeholder="请选择员工" filterable style="width:100%">
                <el-option v-for="emp in employeeOptions" :key="emp.id" :label="emp.name" :value="emp.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="attendanceForm.status" placeholder="请选择状态" style="width:100%">
                <el-option label="正常" :value="1"></el-option>
                <el-option label="迟到" :value="2"></el-option>
                <el-option label="早退" :value="3"></el-option>
                <el-option label="缺勤" :value="4"></el-option>
                <el-option label="请假" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="打卡时间" prop="checkInTime">
              <el-date-picker
                  v-model="attendanceForm.checkInTime"
                  type="datetime"
                  placeholder="选择打卡时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width:100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签退时间" prop="checkOutTime">
              <el-date-picker
                  v-model="attendanceForm.checkOutTime"
                  type="datetime"
                  placeholder="选择签退时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width:100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="notes">
          <el-input v-model="attendanceForm.notes" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>

    <el-card style="margin: 20px;height: 70px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" @change="loadData"></el-input>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadData">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 20px;">
      <el-table :data="attendanceList">
        <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
        <el-table-column label="员工姓名" prop="name" align="center"></el-table-column>
        <el-table-column label="打卡时间" prop="checkInTime" align="center"></el-table-column>
        <el-table-column label="签退时间" prop="checkOutTime" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">{{ formatStatus(row.status) }}</template>
        </el-table-column>
        <el-table-column label="备注" align="center" show-overflow-tooltip>
          <template #default="{row}">{{ row.notes || '无' }}</template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="text" :disabled="getUser.level < 20" @click="editAttendance(scope.row)">编辑</el-button>
            <el-button link type="text" :disabled="getUser.level < 20" @click="deleteAttendance(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px;"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { Message } from 'element-ui'
import qs from "qs";

export default {
  data() {
    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增考勤记录',
      attendanceForm: {
        id: null,
        employeeId: null,
        checkInTime: null,
        checkOutTime: null,
        status: 1,
        notes: ''
      },
      rules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'blur' }],
        checkInTime: [{ required: true, message: '请选择打卡时间', trigger: 'change' }]
      },
      searchForm: {
        employeeName: '',
        dateRange: []
      },
      attendanceList: [],
      employeeOptions: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadEmployees()
  },
  methods: {
    loadData() {
      const data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        employeeName: this.searchForm.employeeName,
        startDate: this.searchForm.dateRange?.[0],
        endDate: this.searchForm.dateRange?.[1]
      });

      axios.get(this.$BASE_URL + '/v1/attendance/list?'+data)
          .then(res => {
            console.log(res.data);
            if (res.data.state === 2000) {
              this.attendanceList = res.data.data.attendanceList;
              this.pagination.total = res.data.data.total;
            } else {
              Message.error(res.data.message)
            }
          })
    },

    loadEmployees() {
      axios.get(this.$BASE_URL + '/v1/user/list')
          .then(res => {
            if (res.data.state === 2000) {
              this.employeeOptions = res.data.data.userList;
            }
          })
    },

    clockIn(){
      let employeeId = this.getUser.id
      axios.post(this.$BASE_URL + `/v1/attendance/clockIn/${employeeId}`)
          .then(res => {
            if (res.data.state === 2000){
              Message.success('打卡成功');
              this.loadData()
            }else {
              Message.error(res.data.message);
            }
          })
    },

    formatStatus(status) {
      const statusMap = ['', '正常', '迟到', '早退', '缺勤', '请假']
      return statusMap[status] || ''
    },

    beforeAddAttendance() {
      this.dialogTitle = '新增考勤记录'
      this.dialogVisible = true
    },

    editAttendance(row) {
      this.dialogTitle = '编辑考勤记录'
      this.attendanceForm = { ...row }
      this.dialogVisible = true
    },

    deleteAttendance(id) {
      this.$confirm('确定删除该记录吗？', '提示', {type: 'warning'})
          .then(() => {
            axios.post(this.$BASE_URL + `/v1/attendance/delete/${id}`)
                .then(res => {
                  if (res.data.state === 2000) {
                    Message.success('删除成功')
                    this.loadData()
                  } else {
                    Message.error(res.data.message)
                  }
                })
          })
          .catch(() => {
          })
    },

    submit() {
      this.$refs.attendanceForm.validate(valid => {
        if (valid) {
          axios.post(this.$BASE_URL +'/v1/attendance/save', qs.stringify(this.attendanceForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('操作成功')
                  this.handleClose()
                  this.loadData()
                } else {
                  Message.error(res.data.message)
                }
              })
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$refs.attendanceForm.resetFields()
      this.attendanceForm = {
        id: null,
        employeeId: null,
        checkInTime: null,
        checkOutTime: null,
        status: 1,
        notes: ''
      }
    },

    resetSearch() {
      this.searchForm = {
        employeeName: '',
        dateRange: []
      }
      this.pagination.current = 1
      this.loadData()
    },

    handleSizeChange(size) {
      this.pagination.size = size
      this.loadData()
    },

    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadData()
    }
  }
}
</script>

<style scoped>
.el-card {
  margin: 20px;
}

.el-form--inline .el-form-item {
  margin-bottom: 0;
}
</style>